package server.tasks;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.Callable;
import javax.sql.XAConnection;
import javax.transaction.xa.XAResource;
import org.postgresql.xa.PGXADataSource;
import server.Logger;
import server.NodeInfo;
import server.SqlHandler;

import java.util.concurrent.Future;
import server.UpdateXid;

public class UpdateTask implements Callable<UpdateTask> {
	private String sql;
	private Connection connection;
	private XAConnection xaConnnection;
	private XAResource resource;
	private NodeInfo node;
	private UpdateXid xid;
	
	public Integer PrepareResult;
	public Integer UpdateCount;
	public Future<UpdateTask> future;
	
	
	public UpdateTask(UpdateXid xid, NodeInfo node, String sql){
		this.setNode(node);
		this.sql = sql;
		this.setXid(xid);
	}

	@Override
	public UpdateTask call() throws Exception {	
		try {			
			PGXADataSource source = new PGXADataSource();
			SqlHandler.prepareXASource(source, getNode());				
			xaConnnection = source.getXAConnection();			
			setResource(xaConnnection.getXAResource());
			connection = xaConnnection.getConnection();					
			getResource().start(getXid(), XAResource.TMNOFLAGS);
			Statement stmt = connection.createStatement();
			UpdateCount = stmt.executeUpdate(sql);  //jesli update nie dochodzi to prawdopodobnie baza jest zapchana transakcjami - trupami
			getResource().end(getXid(), XAResource.TMSUCCESS);
			PrepareResult = getResource().prepare(getXid());		
		} catch (Exception ex) {
			Logger.logEvent("Blad wykonania update task" + ex.getMessage(), Logger.LOG_ERROR);
			throw ex;
			//obsluzyc wyjatek PSQLException "prepared transactions are disabled"!	
		}
		return this;
	}
	
	public void dispose() {
		//zamkniecie polaczen zwiazanych tym taskiem
		try {
			if(xaConnnection != null)
				xaConnnection.close();		
		} catch (SQLException e) {	
		}				
		
		try {
			if(connection != null)
				connection.close();
		} catch (SQLException e) {
		}		
	}

	public void setResource(XAResource resource) {
		this.resource = resource;
	}

	public XAResource getResource() {
		return resource;
	}

	public void setXid(UpdateXid xid) {
		this.xid = xid;
	}

	public UpdateXid getXid() {
		return xid;
	}

	public void setNode(NodeInfo node) {
		this.node = node;
	}

	public NodeInfo getNode() {
		return node;
	}
}